<template>
  <div>
    <h1>选择文件夹并提取最新图片中的文字</h1>
    <input type="file" @change="handleFolderSelect" webkitdirectory multiple />
    <button @click="getLatestImageText" :disabled="!latestImage">提取文字</button>
    <div v-if="latestImage">
      <h2>最新图片：</h2>
      <p>{{ latestImage.name }}</p>
      <img :src="latestImageUrl" alt="Latest Image" width="300" />
    </div>
    <div v-if="extractedText">
      <h2>提取的文字：</h2>
      <p>冀F·{{ extractedText }}</p>
    </div>
    <div v-if="loading">正在提取文字...</div>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import Tesseract from 'tesseract.js';

// 定义响应式变量
const latestImage = ref<File | null>(null);
const latestImageUrl = ref<string | null>(null);
const extractedText = ref<string>('');
const loading = ref<boolean>(false);
const error = ref<string | null>(null);

// 模拟文件夹（用于开发和测试，实际操作中由用户选择文件夹）
const simulatedFolder = [
  new File([""], "image1.png", { type: "image/png", lastModified: Date.now() - 10000 }),
  new File([""], "image2.png", { type: "image/png", lastModified: Date.now() - 5000 }),
  new File([""], "image3.jpg", { type: "image/jpeg", lastModified: Date.now() - 2000 }),
];

// 处理文件夹选择和提取文字
const handleFolderSelect = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const files = Array.from(input.files || []).filter(file =>
      file.type.startsWith('image/') // 只选择图片文件
  );

  // 获取最新的图片
  latestImage.value = getLatestImage(files);
  if (latestImage.value) {
    latestImageUrl.value = URL.createObjectURL(latestImage.value);
    error.value = null; // 清除之前的错误
  }
};

// 获取最新的图片
const getLatestImage = (files: File[]) => {
  return files.reduce((latest, file) => {
    return !latest || file.lastModified > latest.lastModified ? file : latest;
  }, null as File | null);
};

// 提取最新图片中的文字
const getLatestImageText = async () => {
  if (latestImage.value) {
    loading.value = true;
    error.value = null; // 清除之前的错误
    try {
      const { data: { text } } = await Tesseract.recognize(latestImage.value, 'chi_sim'); // 使用简体中文语言
      extractedText.value = text;
    } catch (err) {
      console.error('提取文字失败:', err);
      error.value = '提取文字失败，请重试。';
    } finally {
      loading.value = false;
    }
  }
};
</script>

<style scoped>
/* 样式根据需要调整 */
.error {
  color: red;
}
</style>
